#!/usr/bin/python
#coding:utf-8
'''
    基于python3，解决plt不能显示中文问题
    网址：https://blog.csdn.net/u010758410/article/details/71743225
'''

import numpy as np 
import matplotlib.pyplot as plt
from sklearn.ensemble import IsolationForest

from pylab import mpl

mpl.rcParams['font.sans-serif'] = ['FangSong'] # 指定默认字体
mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题


rng = np.random.RandomState(42)

#Generate train data
x=0.3 * rng.randn(100,2)
x_train = np.r_[x+1,x-3,x-5,x+6]

x= 0.3* rng.randn(20,2)
x_test= np.r_[x+1,x-3,x-5,x+6]

x_outliers=rng.uniform(low=-8,high=8,size=(20,2))

clf=IsolationForest(max_samples=100*2,random_state=rng)
clf.fit(x_train)
y_pred_train = clf.predict(x_train)
y_pred_outliers= clf.predict(x_outliers)

xx,yy=np.meshgrid(np.linspace(-8,8,50),np.linspace(-8,8,50))
z=clf.decision_function(np.c_[xx.ravel(),yy.ravel()])
z=z.reshape(xx.shape)

plt.title("IsolationForest")
plt.contourf(xx,yy,z,cmap=plt.cm.Blues_r)

b1= plt.scatter(x_train[:,0],x_train[:,1],c='white')
b2=plt.scatter(x_test[:,0],x_test[:,1],c='green')
c=plt.scatter(x_outliers[:,0],x_outliers[:,1],c='red')
plt.axis('tight')
plt.xlim((-8,8))
plt.ylim((-8,8))
plt.legend([b1,b2,c],
            ["训练集",  #训练集
            "测试集合","异常点"], #测试集 异常点
            loc="upper left")
plt.show()